//
//  StatsWindow.m
//  KotnetAutologin
//
//	handle statistic window
//
//  Created by Kristof Mariën on 20/01/10.
//  Copyright 2010 KotnetAutologin. All rights reserved.
//

#import "StatsWindow.h"


@implementation StatsWindow
/**
 *  show the statistic window
 */
- (void) show:(id)sender
{
	[NSApp activateIgnoringOtherApps:YES];
	statsWindow = [[NSWindowController alloc] initWithWindowNibName:@"Stats"];
	[[statsWindow window] center];
	[statsWindow showWindow:sender];
	
	downloaded = [[[[statsWindow window] contentView] subviews] objectAtIndex:0];
	uploaded = [[[[statsWindow window] contentView] subviews] objectAtIndex:1];
	progress = [[[[statsWindow window] contentView] subviews] objectAtIndex:8];
	[self loadData:self];
}
/**
 *  load the data
 */
- (void) loadData:(id)sender
{
	[progress startAnimation:sender];
	login = [KotnetLogin alloc];
	[login login:self cannotLoginSelector:@selector(errorLoading) loggedInSelector:@selector(dataLoaded:)];
}
/**
 *  data loaded
 */
- (void) dataLoaded:(NSString *)data
{
	[login release];
	NSString *searchDowload = @"<!-- weblogin: available download = ";
	NSString *searchUpload = @"<!-- weblogin: available upload = ";
	NSRange rangeDownload = [data rangeOfString:searchDowload];
	NSRange rangeUpload = [data rangeOfString:searchUpload];

	NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
	[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
	if (rangeDownload.location != NSNotFound) {
		NSString *download = [data substringFromIndex:rangeDownload.location + rangeDownload.length];
		rangeDownload = [download rangeOfString:@" "];
		[downloaded setDoubleValue:[[download substringToIndex:rangeDownload.location] doubleValue]/1000000];
	}
	if (rangeUpload.location != NSNotFound) {
		NSString *upload = [data substringFromIndex:rangeUpload.location + rangeUpload.length];
		rangeUpload = [upload rangeOfString:@" "];
		[uploaded setDoubleValue:[[upload substringToIndex:rangeUpload.location] doubleValue]/1000000];
	}
	[progress setHidden:YES];
	[progress stopAnimation:self];
}
/**
 *  error loading data
 */
- (void) errorLoading
{
	[self loadData:self];
}

@end
